package com.hxs.hxsserver.controller.device;
import com.hxs.hxsserver.domain.dto.JsonResult;
import com.hxs.hxsserver.domain.dto.device.DeviceSSEDto;
import com.hxs.hxsserver.service.SSEService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@RestController
@Api(value = "硬件对接消息模块")
@RequestMapping("device")
public class SSEController {

    @Resource
    private SSEService sseService;


    @GetMapping("/sse")
    @ApiOperation(value = "接受设备消息")
    public void streamSSE(HttpServletResponse response, HttpServletRequest request, @RequestParam(value = "deviceAddr", required = false) String deviceAddr) throws IOException {
        String ipAddress = request.getRemoteAddr();
        log.info("收到客户端发来的sse请求，ip地址为:"+ ipAddress);
        sseService.streamSSE(response,ipAddress);
    }

    @PostMapping("/command")
    @ApiOperation(value = "发送设备消息")
    public JsonResult<Boolean> command(@RequestBody @Validated DeviceSSEDto deviceSSEDto){
        return JsonResult.success(sseService.command(deviceSSEDto));
    }
}
